<template>
  <div>
    <basic-dialog
      :visible.sync="dialogVisible"
      :handleClose="handleCloseDialog"
      :title="title"
      :show-footer="multiple"
      :width="'60%'"
    >
      <div class="form-container">
        <el-form ref="queryData" :inline="true" :model="queryData" @submit.native.prevent>
          <template v-if="isRegular">
            <el-form-item label="商品代码:" prop="productCode">
              <el-input
                v-model="queryData.productCode"
                placeholder="请输入商品代码"
                @keyup.enter.native="handleQueryData(1)"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品名称:" prop="productName">
              <el-input
                v-model="queryData.productName"
                placeholder="请输入商品名称"
                @keyup.enter.native="handleQueryData(1)"
              ></el-input>
            </el-form-item>
          </template>
          <template v-else>
            <el-form-item label="商品信息:" prop="content">
              <el-input
                v-model="queryData.content"
                placeholder="请输入商品代码或名称"
                @keyup.enter.native="handleQueryData(1)"
              ></el-input>
            </el-form-item>
          </template>
          <el-form-item>
            <el-button type="primary" @click="handleQueryData(1)"
              >查询</el-button
            >
            <el-button @click="handleResetData('queryData')">清空</el-button>
          </el-form-item>
        </el-form>
      </div>
      <BasicTable
        ref="basicTable"
        :loading="tableInfo.loading"
        :columns="tableInfo.columns"
        :dataSource="tableInfo.list"
        :pagination="pagination"
        :pageSizes="pageSizes"
        :tableHeight="443"
        :showSelectCol="multiple"
        :check-selectable="checkSelectable"
        :selection-change="selectionChange"
        :showActionCol="!multiple"
        :actionRender="actionRender"
        @rowDblclick="handleSelectRow"
        @pageChange="handlePageChange"
        @pageSizeChange="handlePageSizeChange"
        @handleSortChange="handleSortChange"
      />
      <el-row type="flex" justify="center" slot="ft" v-if="multiple">
        <el-button
          type="primary"
          v-preventReClick
          :disabled="!tableInfo.selection.length"
          @click="handleSubmitSelections"
        >确定关联</el-button>
        <el-button @click="handleCloseDialog">取消</el-button>
      </el-row>
    </basic-dialog>
  </div>
</template>
<script>
import { mapGetters } from 'vuex';
import BasicDialog from '@/components/BasicDialog';
import BasicTable from '@/components/supplier/BasicTable';
import { getBtnsId } from '@/libs/btnsPermission';
import {
  queryRegularRelationProductListService, // 正常价格关联商品
} from '@api/supplier/supervision/regularPrice';
import {
  queryTempRelationProductListService, // 临采价格核查关联商品
} from '@api/supplier/supervision/tempPrice';
import { isResponseSuccess } from '@/pages/supplier/utils/bizUtils';

export default {
  name: 'SelectProductDialog',
  components: {
    BasicDialog,
    BasicTable,
  },
  props: {
    title: { type: String, default: '关联商品' }, // 弹窗标题
    dialogVisible: { type: Boolean, default: false }, // 弹窗显隐
    type: { type: String, default: 'regular' }, // 类型： regular正常商品 temp 临采商品
    supplierId: { type: Number, default: 0 }, // 供应商 ID
    supplierCode: { type: [String, Number] }, // 供应商 Code
    areaId: { type: [String, Number] }, // 核查区域 ID
    areaCode: { type: [String, Number] }, // 核查区域 Code
    multiple: { type: Boolean, default: false }, // 是否多选
  },
  data () {
    let columns = [
      { title: '商品代码', key: 'productCode', width: 120, sortable: true },
      { title: '商品名称', key: 'productName', width: 240 },
      { title: '规格', key: 'specification', },
      { title: '单位', key: 'unit' },
    ]
    if (this.type === 'regular') {
      columns = columns.concat([
        { title: '上年度进货数量', key: 'lastYearPurchaseCount', width: 120 },
        { title: '上年度进货金额', key: 'lastYearPurchaseAmount', width: 120 },
        { title: '本年度采购数量', key: 'thisYearPurchaseCount', width: 120 },
        { title: '本年度采购金额', key: 'thisYearPurchaseAmount', width: 120 },
        { title: '单价', key: 'price' },
      ])
    }
    return {
      queryData: {
        productCode: '', // 商品代码
        productName: '', // 商品名称
        content: '', // 商品代码+名称
        sort: 1 // 1 升序，2 降序
      },
      pageSizes: [100, 200],
      pagination: {
        current: 1,
        total: 0,
        size: 100
      },
      tableInfo: {
        list: [],
        loading: false,
        selection: [],
        columns,
      }
    };
  },
  computed: {
    ...mapGetters('permissions/systemBtns', ['showBtn']),
    isRegular () {
      return this.type === 'regular'
    }
  },
  methods: {
    // 排序
    handleSortChange ({ prop, order }) {
      if (order == 'ascending') {
        this.queryData.sort = 1
      }
      if (order == 'descending') {
        this.queryData.sort = 2
      }
      this.handleQueryData(1)
    },
    // 操作列
    actionRender (h, { row }) {
      return (
        <div class="table-action">
          <el-button
            size="mini"
            type="text"
            onClick={() => this.handleSelectRow(row)}
          > 选择
          </el-button>
        </div>
      );
    },
    handleSelectRow (row) {
      if (!this.multiple) {
        this.$emit('handle-select', row);
        this.handleCloseDialog();
      }
    },
    // 确定关联
    handleSubmitSelections () {
      this.$emit('handle-select', this.tableInfo.selection);
      this.handleCloseDialog();
    },
    // 勾选需要处理
    selectionChange (rows) {
      this.tableInfo.selection = rows;
    },
    // CheckBox 是否可以勾选
    checkSelectable ({ row }) {
      // console.log('row :>> ', row);
      return true
    },
    // 获取 表格数据
    handleQueryData (pageNum) {
      const { supplierCode, isRegular, pagination, queryData, areaCode } = this
      const { content, productCode, productName, sort } = queryData
      const { size } = pagination
      if (!supplierCode && isRegular) {
        this.$message.error('请先选择供应商')
        this.handleCloseDialog()
        return
      }
      this.tableInfo.loading = true;
      sessionStorage.setItem('buttonId', getBtnsId('查询'));
      if (isRegular) {
        // 正常价格关联商品)
        queryRegularRelationProductListService({
          // areaId: parseInt(areaId, 10),
          itemAreaCode: areaCode,
          supplyUuid: supplierCode,
          skuNo: productCode,
          productName,
          supplierCode,
          nowPage: pageNum,
          pageShow: size,
          sort
        })
          .then(res => {
            this.tableInfo.loading = false;
            if (isResponseSuccess(res)) {
              const { records, total, current } = res.result;
              this.tableInfo.list = records;
              this.pagination.total = total;
              this.pagination.current = current;
              this.reloadTableLayout()
            }
          }).catch(() => {
            this.tableInfo.loading = false;
          });
      } else {
        // 临采价格关联商品
        queryTempRelationProductListService({ content, sort, current: pageNum, size, })
          .then(res => {
            this.tableInfo.loading = false;
            if (isResponseSuccess(res)) {
              const { records, total, current } = res.result;
              this.tableInfo.list = records;
              this.pagination.total = total;
              this.pagination.current = current;
              this.reloadTableLayout()
            }
          }).catch(() => {
            this.tableInfo.loading = false;
          });
      }
    },
    // 分页状态变更
    handlePageChange (pageNum) {
      this.handleQueryData(pageNum);
    },
    // 分页状态变更
    handlePageSizeChange (pageSize) {
      this.pagination.size = pageSize;
      this.handleQueryData(1);
    },
    // 重置查询条件
    handleResetData (formName) {
      this.$refs[formName].resetFields();
    },
    // 关闭弹框
    handleCloseDialog () {
      this.$emit('update:dialogVisible', false);
      this.handleResetData('queryData')
      this.pagination = { current: 1, total: 0, size: 100 }
      this.tableInfo.list = []
      this.tableInfo.selection = []
    },
    // 表格DOM重新渲染
    reloadTableLayout () {
      this.$nextTick(() => {
        this.$refs.basicTable.$refs.elTable.doLayout();
      });
    },
  }
};
</script>
<style scoped>
.form-container {
  margin-bottom: 10px;
}
</style>
